package cn.stylefeng.guns.modular.rest.storage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.entity.BasicTray;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicTrayParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicTrayResult;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicTrayService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.entity.OrderPut;
import cn.stylefeng.guns.modular.order.model.params.OrderPutDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutResult;
import cn.stylefeng.guns.modular.order.service.OrderPutDetailedService;
import cn.stylefeng.guns.modular.order.service.OrderPutService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storage.entity.StorageAllocationOut;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageAllocationOutDetailedParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageAllocationOutParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageAllocationOutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageAllocationOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageAllocationOutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutSingleService;
import cn.stylefeng.guns.modular.storage.service.StorageStockDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * rest
 * 调拨出库
 */
@Controller
@RequestMapping("/rest/storageAllocationOut")
public class reststorageAllocationOutController extends BaseController {

    @Autowired
    private StorageAllocationOutDetailedService storageAllocationOutDetailedService;
    
    @Autowired
    private StorageStockService storageStockService;
    
    @Autowired
    private UserAop userAop;
    
    /**
     * 查询 调拨明细
     */
    @ResponseBody
    @RequestMapping("/findDetailedlist")
    public ResponseData findDetailedlist(StorageAllocationOutDetailedParam storageAllocationOutDetailedParam) {
        return ResponseData.success(this.storageAllocationOutDetailedService.findListBySpec(storageAllocationOutDetailedParam));
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(StorageAllocationOutDetailedParam storageAllocationOutDetailedParam) {
        this.storageAllocationOutDetailedService.delete(storageAllocationOutDetailedParam);
        return ResponseData.success();
    }

    @Autowired
    private BasicGoodsService basicGoodsService;

    /**
     * 新增 调拨明细
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResponseData add(StorageStockParam storageStockParam) {
    	if(storageStockParam == null) {
    		return ResponseData.error("Parameters are empty");
    	}
    	BigDecimal as = new BigDecimal(0);
    	BigDecimal dbnum = new BigDecimal(storageStockParam.getNum());//调拨数量
    	StorageStock storageStock = storageStockService.getById(storageStockParam.getId());
    	BigDecimal kcnum = new BigDecimal(storageStock.getNum());//库存数量
    	if(dbnum.compareTo(as) == 0 || dbnum.compareTo(as) == -1) {
    		return ResponseData.error("Please enter correct allocation quantity");
    	}
    	if(dbnum.compareTo(kcnum) == 1) {
    		return ResponseData.error("Allocation quantity cannot be greater than tray inventory");
    	}
    	
    	BasicGoods basicGoods = basicGoodsService.getById(storageStockParam.getGoodsId());
    	StorageAllocationOutDetailedParam storageAllocationOutDetailedParam = new StorageAllocationOutDetailedParam();
    	storageAllocationOutDetailedParam.setStockId(Long.parseLong(storageStockParam.getId().toString()));
    	storageAllocationOutDetailedParam.setAllocationOrderNumber(storageStockParam.getAllocationOrderNumber());
    	storageAllocationOutDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
    	storageAllocationOutDetailedParam.setPositionId(storageStockParam.getPositionId());
    	storageAllocationOutDetailedParam.setStoragePostionNumber(storageStockParam.getPositionNumber());
    	storageAllocationOutDetailedParam.setStorageGoodsId(storageStockParam.getGoodsId());
    	storageAllocationOutDetailedParam.setStorageGoodscode(storageStockParam.getGoodsNumber());
    	storageAllocationOutDetailedParam.setStorageGoodsname(storageStockParam.getGoodsName());
    	storageAllocationOutDetailedParam.setStorageNumber(storageStockParam.getNum());
    	
    	BigDecimal goodsWeight = new BigDecimal(basicGoods.getGoodsWeight());
    	BigDecimal goodsVolume = new BigDecimal(basicGoods.getGoodsVolume());
    	BigDecimal goodsCharging = new BigDecimal(basicGoods.getGoodsCharging());
    	
    	storageAllocationOutDetailedParam.setStorageWeight(dbnum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
    	storageAllocationOutDetailedParam.setStorageVolume(dbnum.multiply(goodsVolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
    	storageAllocationOutDetailedParam.setStorageMoney(dbnum.multiply(goodsCharging).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
    	storageAllocationOutDetailedParam.setStoragePrice(storageStockParam.getUnitprice());
    	
    	storageAllocationOutDetailedParam.setStorageBatchnumber(storageStockParam.getGoodsbatchs());
    	storageAllocationOutDetailedParam.setStorageDate(storageStockParam.getProducetime());
    	storageAllocationOutDetailedParam.setStorageLargeclass(basicGoods.getGoodsBigtype());
    	storageAllocationOutDetailedParam.setStorageGoodstype(basicGoods.getGoodsType());
    	storageAllocationOutDetailedParam.setGoodsUnit(basicGoods.getGoodsUnit());
    	storageAllocationOutDetailedParam.setGoodsSpecs(basicGoods.getGoodsSpecs());
    	storageAllocationOutDetailedParam.setV1(storageStockParam.getPutTime());
    	storageAllocationOutDetailedParam.setV2(basicGoods.getGoodsNo());
        this.storageAllocationOutDetailedService.add(storageAllocationOutDetailedParam);
        return ResponseData.success();
    }

    @Autowired
    private OrderPutService orderPutService;

	@Autowired
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
    
    /**
     * 提交  调拨
     */
    @RequestMapping("/addAllocation")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout=300)
    public ResponseData addAllocation(StorageAllocationOutParam storageAllocationOutParam) {
    	User user = userAop.getUser();
		String trayCode = getOperateIdOrderPrefix(user);
    	storageAllocationOutParam.setDeliverId(user.getDeliverId());
    	storageAllocationOutParam.setDeptId(user.getDeptId());
    	storageAllocationOutParam.setStatus("COMPLETED");
    	
    	StorageAllocationOutDetailedParam storageAllocationOutDetailedParam = new StorageAllocationOutDetailedParam();
    	storageAllocationOutDetailedParam.setAllocationOrderNumber(storageAllocationOutParam.getAllocationOrderNumber());
		List<StorageAllocationOutDetailedResult> list = storageAllocationOutDetailedService.findListBySpec(storageAllocationOutDetailedParam);//查询明细
		if(list.size() == 0) {
			return ResponseData.error("Please add allocation details first");
		}
		
		OrderPutParam orderPutParam = new OrderPutParam();
		orderPutParam.setDeliverId(user.getDeliverId());
		orderPutParam.setDeptId(user.getDeptId());//set 部门id
		orderPutParam.setWarehouseName(storageAllocationOutParam.getWarehousePutName());
		orderPutParam.setWarehouseId(Long.parseLong(storageAllocationOutParam.getWarehousePutId().toString()));
		orderPutParam.setPutCustomerId(storageAllocationOutParam.getCustomerId());
		orderPutParam.setPutCustomerName(storageAllocationOutParam.getCustomerName());
		orderPutParam.setBillstate("PENDING_SUBMIT");
		orderPutParam.setCreateName(user.getName());
    	OrderPut orderPut = this.orderPutService.findByThelastone();
    	if (orderPut!=null) {
    		orderPutParam.setPutNumber(trayCode+"-"+"DBRK-"+DateUtil.getDateBch()+"-"+(orderPut.getId()+1));
		} else {
			orderPutParam.setPutNumber(trayCode+"-"+"DBRK-"+DateUtil.getDateBch()+"-"+"1");
		}
    	orderPutParam.setPutMode("WAREHOUSE_RECEIVING");
    	orderPutParam.setPutCustomerNumber(storageAllocationOutParam.getAllocationOrderNumber());
    	orderPutParam.setEstimatetime(DateUtil.getDate());
    	orderPutParam.setPutType("TRANSFER_IN");
		List<OrderPutDetailedParam> detailedList = new ArrayList<OrderPutDetailedParam>();//批量保存的 调拨入库订单商品明细list
		
		for (StorageAllocationOutDetailedResult r : list) {
	    	StorageStock storageStock = storageStockService.getById(r.getStockId());
	    	if(storageStock == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("Inventory has changed!");//库存不存在了
	    	}

	    	BigDecimal as = new BigDecimal(0);
	    	BigDecimal dbnum = new BigDecimal(r.getStorageNumber());//调拨数量
	    	BigDecimal kcnum = new BigDecimal(storageStock.getNum());//库存数量
	    	if(kcnum.compareTo(as) == 0 || kcnum.compareTo(as) == -1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("Inventory has changed!");//库存数等于0或者小于0
	    	}
			if(dbnum.compareTo(kcnum) == 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                return ResponseData.error("Inventory has changed!");//调拨数量超出库存数量
			}
			
	    	BasicGoods basicGoods = basicGoodsService.getById(r.getStorageGoodsId());
			//创建订单明细
			OrderPutDetailedParam opdpDetailedParam = new OrderPutDetailedParam();
			opdpDetailedParam.setPutDetailedNumber(orderPutParam.getPutNumber());//入库订单编号
			opdpDetailedParam.setDetailedGoodsname(r.getStorageGoodsname());//商品名称
			opdpDetailedParam.setDetailedGoodsnum(Long.parseLong(r.getStorageGoodsId().toString()));//商品id
			opdpDetailedParam.setGoodsNumber(r.getStorageGoodscode());//商品编号
			opdpDetailedParam.setGoodsNo(basicGoods.getGoodsNo());
			
			opdpDetailedParam.setDetailedPutbalenum(r.getStorageNumber());//应入大包数
			opdpDetailedParam.setDetailedPutnum(r.getStorageNumber());//应入数量
			opdpDetailedParam.setDetailedPutweight(r.getStorageWeight());//应入重量
			opdpDetailedParam.setGoodsWeight(basicGoods.getGoodsWeight());//重量
			opdpDetailedParam.setDetailedPutvolume(r.getStorageVolume());//应入体积
			opdpDetailedParam.setGoodsVolume(basicGoods.getGoodsVolume());//体积
			opdpDetailedParam.setDetailedUnitprice(r.getStoragePrice());//单价
			opdpDetailedParam.setDetailedMoney(r.getStorageMoney());//金额
			
			opdpDetailedParam.setDetailedBatchnumber(r.getStorageBatchnumber());//批次
			opdpDetailedParam.setDetailedDateofmanufacture(r.getStorageDate());//生产日期
			opdpDetailedParam.setRecommend(storageStock.getPutTime());//推荐批次
			
			opdpDetailedParam.setDetailedRebubbles(basicGoods.getGoodsHeavybubble());//重泡货
			opdpDetailedParam.setDetailedLargeclass(basicGoods.getGoodsBigtype());//商品大类 (导入品类描述)
			opdpDetailedParam.setDetailedGoodstype(basicGoods.getGoodsType());//商品类别
			opdpDetailedParam.setDetailedPutcondition(basicGoods.getGoodsCondition());//保管条件
			opdpDetailedParam.setDetailedPacking(basicGoods.getGoodsPacking());//包装
			opdpDetailedParam.setGoodsSpecs(basicGoods.getGoodsSpecs());
			opdpDetailedParam.setGoodsUnit(basicGoods.getGoodsUnit());
			opdpDetailedParam.setCreateTime(new Date());
			detailedList.add(opdpDetailedParam);
			opdpDetailedParam = new OrderPutDetailedParam();
			if(dbnum.compareTo(kcnum) == 0) {
				//调拨数量 与 库存数量 相等
				StorageStockParam storageStockParam = new StorageStockParam();
				storageStockParam.setId(storageStock.getId());
				storageStockDetailedService.addNewDetailedstorageStock("TRANSFER_OUT", storageAllocationOutParam.getAllocationOrderNumber(), "OUTBOUND", "INBOUND WAREHOUSE:"+storageAllocationOutParam.getWarehousePutName(), storageStock, user);
				storageStockService.delete(storageStockParam);
				try {
					StorageStockParam param222 = new StorageStockParam();
					param222.setTrayId(storageStock.getTrayId());
					StorageStockResult storageStockResult = storageStockService.findBySpec(param222);
					if (storageStockResult == null) {
						BasicTrayParam basicTrayParam = new BasicTrayParam();
						basicTrayParam.setId(Integer.parseInt(storageStock.getTrayId().toString()));
						basicTrayParam.setTrayState("IDLE");
						basicTrayService.update(basicTrayParam);
					}
				} catch (Exception e) {
				}
			}
			if(dbnum.compareTo(kcnum) == -1) {
				//调拨数量 小于 库存数量
				StorageStockParam param2 = new StorageStockParam();
				BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());
				BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
				BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
       			BigDecimal less = kcnum.subtract(dbnum);
	       		storageStock.setNum(less.setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       		storageStock.setCanNum(less.setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       		storageStock.setBalenum(less.setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       		storageStock.setStockWeight(less.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       		storageStock.setStockVolume(less.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       		storageStock.setStockMoney(less.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				ToolUtil.copyProperties(storageStock,param2);
				storageStockDetailedService.addNewDetailed("TRANSFER_OUT", storageAllocationOutParam.getAllocationOrderNumber(), "OUTBOUND", "OUTBOUND:"+dbnum.toString()+"INBOUND WAREHOUSE:"+storageAllocationOutParam.getWarehousePutName(), param2, user);
				storageStockService.update(param2);
			}
		}
		this.storageAllocationOutService.add(storageAllocationOutParam);
		orderPutService.add(orderPutParam);
		
		if(detailedList.size()>0){
			orderPutDetailedService.saveBatchList(detailedList);
		}
		
		OrderPutResult orderPutResult = orderPutService.findBySpec(orderPutParam,user.getOperateId());
		OrderPut orderPut2 = orderPutService.getById(orderPutResult.getId());

		try {
			storagePutSingleService.productionPutSingleNew(orderPut2,user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		
        return ResponseData.success();
    }

    @Autowired
    private StorageStockDetailedService storageStockDetailedService;

    @Autowired
    private StoragePutSingleService storagePutSingleService;
    
    @Autowired
    private BasicTrayService basicTrayService;

    @Autowired
    private StorageAllocationOutService storageAllocationOutService;

    @Resource
    private OrderPutDetailedService orderPutDetailedService;

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(StorageAllocationOutParam storageAllocationOutParam,String condition ) {
    	User user = userAop.getUser();
    	storageAllocationOutParam.setDeliverId(user.getDeliverId());
    	storageAllocationOutParam.setDeptId(user.getDeptId());
    	LayuiPageInfo LayuiPageInfo = this.storageAllocationOutService.findPageBySpec(storageAllocationOutParam,condition,user.getOperateId());
    	LayuiPageInfo.setCode(200);
        return LayuiPageInfo;
    }
    
    /**
     *作废
     */
    @ResponseBody
    @RequestMapping("/zuofei")
    public ResponseData zuofei(StorageAllocationOutParam storageAllocationOutParam) {
    	User user = userAop.getUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
    	StorageAllocationOut storageAllocationOut = storageAllocationOutService.getById(storageAllocationOutParam.getId());
    	OrderPutParam OrderPutParam = new OrderPutParam();
    	OrderPutParam.setPutCustomerNumber(storageAllocationOut.getAllocationOrderNumber());
    	OrderPutResult orderPutResult = orderPutService.findBySpec(OrderPutParam,null);
        if ("PENDING_INBOUND".equals(orderPutResult.getBillstate())|| "WAREHOUSED".equals(orderPutResult.getBillstate())) {
        	ResponseData data = new ResponseData();
        	OrderPut orderPut = orderPutService.getById(orderPutResult.getId());
        	data = orderPutService.revokeS2(orderPut,data,user);
        	if(!data.getSuccess()) {
        		return ResponseData.error("Inbound inventory has changed, cannot void");
        	}
		} else {
	        ToolUtil.copyProperties(orderPutResult,OrderPutParam);
	        orderPutService.delete(OrderPutParam);
		}
        
        StorageAllocationOutDetailedParam storageAllocationOutDetailedParam = new StorageAllocationOutDetailedParam();
        storageAllocationOutDetailedParam.setAllocationOrderNumber(storageAllocationOut.getAllocationOrderNumber());
		List<StorageAllocationOutDetailedResult> list = storageAllocationOutDetailedService.findListBySpec(storageAllocationOutDetailedParam);
        
        if (list.size()>0) {
    		List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list

    		StorageStockParam ssP = new StorageStockParam();//库存输入类
    		BasicTrayParam Tp = new BasicTrayParam();
    		BasicTray basicTray = basicTrayService.findByThelastone();

    		Tp.setTrayState("OCCUPIED");//托盘状态
    		Integer TrayNumber = null;
    		String trayCode = getOperateIdOrderPrefix(user)+"-";
    		if (basicTray!=null) {
    			TrayNumber = (basicTray.getId()+1);
    		} else {
    			TrayNumber = 1;
    		}
    		Tp.setDeliverId(deliverId);
    		Tp.setDeptId(deptId);
        	for (StorageAllocationOutDetailedResult detailedResult : list) {
	    		BigDecimal as = new BigDecimal(0);
	    		BigDecimal realNum = new BigDecimal(detailedResult.getStorageNumber());
	    		if (realNum.compareTo(as)==0) {
					continue;
				}
				
        		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
        		BasicTrayParam btp = new BasicTrayParam();//托盘输入类
        		BasicGoods basicGoods = basicGoodsService.getById(detailedResult.getStorageGoodsId());
        		BasicWarehouse basicWarehouse = basicWarehouseService.getById(storageAllocationOut.getWarehouseOutId());
    			bpp.setPositionNumber(detailedResult.getStoragePostionNumber());
    			bpp.setWarehouseId(basicWarehouse.getId());
    			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,null,null);//库位信息
    			btp.setTrayNumber(detailedResult.getTrayNumber());
    			btp.setDeptId(deptId);
    			btp.setDeliverId(deliverId);
    			BasicTrayResult bTr = basicTrayService.findBySpec(btp,user.getOperateId());
    			
            	StorageStockParam param2 = new StorageStockParam();
            	param2.setStockstate("IN_STOCK");
            	param2.setGoodsId(detailedResult.getStorageGoodsId());
            	param2.setWarehouseId(Long.parseLong(storageAllocationOut.getWarehouseOutId().toString()));
            	param2.setTrayNumber(detailedResult.getTrayNumber());
            	param2.setGoodsbatchs(detailedResult.getStorageBatchnumber());
            	StorageStockResult storageStock = storageStockService.findBySpec(param2);
            	if (storageStock!=null) {
    	    		BigDecimal b = new BigDecimal(storageStock.getNum());
    	    		b = b.add(realNum);
            		try {
                		BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
                		BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                		BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
                		storageStock.setStockVolume(b.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                		storageStock.setStockWeight(b.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                		storageStock.setStockMoney(b.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} catch (Exception e) {
					}
            		
    	    		storageStock.setNum(b.toString());
    	    		storageStock.setBalenum(b.toString());
    	    		storageStock.setCanNum(b.toString());

    				ToolUtil.copyProperties(storageStock,param2);
	                storageStockDetailedService.addNewDetailed("TRANSFER_OUT", "", "REVOKE_TRANSFER", "INVENTORY ADD:"+realNum.toString(), param2,user);
    				storageStockService.update(param2);
				} else {
					//库存明细
					if(bTr == null || bTr.getTrayState().equals("OCCUPIED")) {
						BasicTrayParam trayParam = new BasicTrayParam();
						trayParam.setDeliverId(deliverId);
						trayParam.setDeptId(deptId);
						trayParam.setTrayState("IDLE");
						BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
						if (basicTrayResult != null) {
							basicTrayResult.setTrayState("OCCUPIED");
							ToolUtil.copyProperties(basicTrayResult, trayParam);
							basicTrayService.update(trayParam);
			    			ssP.setTrayId(Long.parseLong(trayParam.getId().toString()));//托盘id
			    			ssP.setTrayNumber(trayParam.getTrayNumber());//托盘编号
						} else {
							Tp.setTrayNumber(trayCode+TrayNumber);
							basicTrayService.add(Tp);
							basicTrayResult = basicTrayService.findBySpec(Tp,user.getOperateId());
			    			ssP.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));//托盘id
			    			ssP.setTrayNumber(Tp.getTrayNumber());//托盘编号
							TrayNumber++;
						}
					} else {
		    			ssP.setTrayId(Long.parseLong(bTr.getId().toString()));//托盘id
		    			ssP.setTrayNumber(bTr.getTrayNumber());//托盘编号
		    			bTr.setTrayState("OCCUPIED");
						ToolUtil.copyProperties(bTr, btp);
						basicTrayService.update(btp);
					}
	    			ssP.setCustomerId(Long.parseLong(storageAllocationOut.getCustomerId().toString()));//客户id
	    			ssP.setCustomerName(storageAllocationOut.getCustomerName());//客户名称
	    			ssP.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));//分公司id
	    			ssP.setOperateName(basicWarehouse.getWarehouseOperateName());//分公司名称
	    			ssP.setWarehouseId(Long.parseLong(storageAllocationOut.getWarehouseOutId().toString()));//仓库id
	    			ssP.setWarehouseName(storageAllocationOut.getWarehouseOutName());//仓库名称
	    			ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
	    			ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
	    			ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
	    			ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
	    			ssP.setGoodsId(detailedResult.getStorageGoodsId());//商品id
	    			ssP.setGoodsName(detailedResult.getStorageGoodsname());//商品名称
	    			ssP.setGoodsNumber(detailedResult.getStorageGoodscode());//商品编号
	    			ssP.setNum(realNum.toString());//应入数量
	    			ssP.setBalenum(realNum.toString());//应入数量
	    			ssP.setCanNum(realNum.toString());//应入数量
	    			ssP.setStockWeight(detailedResult.getStorageWeight());//应入重量
	    			ssP.setStockVolume(detailedResult.getStorageVolume());//应入体积
	    			ssP.setUnitprice(basicGoods.getGoodsCharging());//单价
	    			ssP.setStockMoney(detailedResult.getStorageMoney());//金额
	    			ssP.setProducetime(detailedResult.getStorageDate());//生产日期
	    			ssP.setGoodsbatchs(detailedResult.getStorageBatchnumber());//批次
	    			ssP.setPutTime(detailedResult.getV1());
	    			ssP.setDeliverId(deliverId);
	    			ssP.setDeptId(deptId);
	    			ssP.setCreateTime(new Date());
	    			ssP.setCreateUser(user.getUserId());
	    			ssP.setStockstate("IN_STOCK");
	    			ssPlist.add(ssP);
	    			ssP = new StorageStockParam();
				}
			}
        	if (ssPlist.size()>0) {
    			storageStockService.batchAddList(ssPlist);
    			for (StorageStockParam p : ssPlist) {
    				try {
    					StorageStockResult result = storageStockService.findBySpec2(p);
    	                storageStockDetailedService.addNewDetailedResult("TRANSFER_OUT", "", "REVOKE_TRANSFER", "", result,user);
					} catch (Exception e) {
					}
				}
			}
		} 
        storageAllocationOutParam.setStatus("VOID");
        this.storageAllocationOutService.update(storageAllocationOutParam);
        
        return ResponseData.success();
    }


    @Resource
    private BasicWarehouseService basicWarehouseService;

    @Resource
    private BasicPositionService basicPositionService;

}
